package EXEX;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import network.MultiChatClient;
import network.SocketData;

public class rspClientThread extends Thread{
	rspserver rs;
	rspClient rc;
	Socket socket;
	boolean tflag = true;
	ObjectOutputStream send;
	ObjectInputStream receive;
	
	int timer = 11;
	boolean timerflag = false;
	
	String finalresult;  //최종 결과
	int win = 0;
	int draw = 0;
	int lose = 0;
	
	public rspClientThread(rspClient r, Socket socket){
		this.rc = r;
		this.socket = socket;
	}
	
	public void run(){
		try{
			send = new ObjectOutputStream(socket.getOutputStream());
			receive = new ObjectInputStream(socket.getInputStream());
			rspData rd = new rspData("login", rc.id.getText(), null);
			send.writeObject(rd);			
			
			while(tflag){
				rd = (rspData)receive.readObject();		
				if(rd.getCommand().equals("gameStart")){
					rc.rbtn.setEnabled(true);
					rc.sbtn.setEnabled(true);
					rc.pbtn.setEnabled(true);
					rd = new rspData("gameStart", "client", null);
					send.writeObject(rd);
					timerflag = true;
					timerrun();
					timerflag = false;
					timer = 11;
					Thread.sleep(10);
					if(rc.rspselect2 != 0){
						rd = new rspData("select", rc.id.getText(), null);
						rd.select = rc.rspselect2;
						send.writeObject(rd);
					}
					else if(rd.select == 0){
						rd = new rspData("select", rc.id.getText(), null);
						rd.select = (int)(Math.random()*3) + 1;
						send.writeObject(rd);
						rc.rbtn.setEnabled(false);
						rc.sbtn.setEnabled(false);
						rc.pbtn.setEnabled(false);		
					}
				}
				else if(rd.getCommand().equals("result")){
					if(rd.getResult().equals("draw")){
						finalresult = "draw";
						draw++;
					}
					else if(rd.getResult().equals("win")){
						finalresult = "lose";
						lose++;
					}
					else if(rd.getResult().equals("lose")){
						finalresult = "win";
						win++;
					}
					rc.userresult.setText(finalresult);
					rc.result.setText("전적 : " + win + " 승 " + draw + " 무 " + lose + " 패 ");
					rc.rspselect2 = 0;  // 결과 나온후 초기화
					rc.readybtn.setEnabled(true);
				}
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}		
	}
	
	public void timerrun(){
		try{
			while(timerflag && timer > 0){
				timer -= 1;
				rc.time2.setText("남은시간 : " + Integer.toString(timer));
				Thread.sleep(1000);
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
}
